package com.oa.mail.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.Tips;
import com.mdp.core.err.BizException;
import com.mdp.core.service.BaseService;
import com.oa.mail.entity.MailAccount;
import com.oa.mail.mapper.MailAccountMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.util.*;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月9日
 */
@Service
public class MailAccountService extends BaseService<MailAccountMapper,MailAccount> {
	static Logger logger =LoggerFactory.getLogger(MailAccountService.class);

	/**
	 * 自定义查询，支持多表关联
	 * @param page 分页条件
	 * @param ew 一定要，并且必须加@Param("ew")注解
	 * @param ext 如果xml中需要根据某些值进行特殊处理，可以通过这个进行传递，非必须，注解也可以不加
	 * @return
	 */
	public List<Map<String,Object>> selectListMapByWhere(IPage page, QueryWrapper ew, Map<String,Object> ext){
		return baseMapper.selectListMapByWhere(page,ew,ext);
	}

	JavaMailSenderImpl emailSender = new JavaMailSenderImpl();
	public String mailProtocol = "smtp";
	public String mailDefaultEncoding = "utf-8";


	@Autowired
	MailEmailService mailEmailService;

	/**
	 * 测试账号是否能发送短信
	 * @param mailAccount
	 */
	public void testAccount(MailAccount mailAccount)  {
		Tips tips = new Tips();

		emailSender.setHost(mailAccount.getSendServer()); //服务器名
		emailSender.setUsername(mailAccount.getEmail());  //用户名
		emailSender.setPassword(mailAccount.getPassword()); //密码
		emailSender.setPort(Integer.parseInt(mailAccount.getSendPort())); //smtp端口
		emailSender.setProtocol(mailProtocol);
		emailSender.setDefaultEncoding(mailDefaultEncoding);

		Properties properties = new Properties();
		String sendIsSsl = mailAccount.getSendIsSsl();
		boolean isSSL = true;
		if (sendIsSsl.equals("0")){
			isSSL = false;
		}
		properties.put("mail.smtp.ssl.enable", isSSL);
		properties.put("mail."+mailProtocol+".auth", true);
		emailSender.setJavaMailProperties(properties);

		try {
			emailSender.testConnection();
		} catch (MessagingException e) {
			tips.setErrMsg(e.getMessage());
			throw new BizException(tips);
		}


	}

	//检查公司账号新邮件数量
	public List<Map<String, Object>> checkMailAccountNewEmail(MailAccount mailAccount) {

		//根据条件获取列表
		List<MailAccount> mailAccounts = this.selectListByWhere(mailAccount);

		List<Map<String,Object>> resluts = new ArrayList<>();
		mailAccounts.forEach((account)->{
			Integer integer = mailEmailService.checkNewEmail(account);
			Map<String, Object> newMap = new HashMap<>();
			newMap.put("email",account.getEmail());
			newMap.put("newEmailNum",integer);
			resluts.add(newMap);
		});
		return resluts;
	}

	/** 请在此类添加自定义函数 */


}

